package service;

import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pojo.User;
import utils.SqlSessionFactoryUtils;

public class UserService {
    //设置factory
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
    public User login(String username,String password){
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.selectByUsername(username);
        if (user !=null){
            //继续比对密码
            if(password.equals(user.getPassword())){
                //登录成功
                return user;
            }else {
                //因为密码错误，导致登录失败
                return null;
            }
        }
        //因为用户不存在导致登录失败
        return null;
    }

    public boolean register(String username, String password){
        User user = new User(null, username, password);
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int result = mapper.add(user);
        sqlSession.commit();
        sqlSession.close();
        return result == 1;
    }

    /**
     * 检查用户名是否存在
     *
     * @param username
     * @return true 存在；false 不存在
     */
    public boolean checkUsername(String username) {
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //1.先检查此用户是否可用被注册
        User user = userMapper.selectByUsername(username);
        if (user != null) {
            //如果此条件成立，代表数据库中已有该名称的用户
            return true;
        }
        sqlSession.close();
        return false;
    }
}





